package io.mya.modules.sys.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import io.mya.common.respentity.ResponseBuilder;
import io.mya.modules.sys.entity.CandyAboutEntity;
import io.mya.modules.sys.entity.CandyUserEntity;
import io.mya.modules.sys.entity.TokenInfoEntity;
import io.mya.modules.sys.service.*;
import io.mya.modules.sys.vo.PrometorUserStatistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 糖果主要Controller
 */
@RestController
@RequestMapping("/candybox")
public class CandyController {

    private final String BIGKEY = "candy party";

    private final String MAILMARK = "mailmark";


    @Value("${sysUse.rsaKey}")
    private String rsaKey;

    @Value("${candyMail.host}")
    private String host;

    @Value("${candyMail.port}")
    private String port;

    @Value("${candyMail.from}")
    private String from;

    @Value("${candyMail.user}")
    private String user;

    @Value("${candyMail.passwd}")
    private String passwd;


    @Autowired
    private CandyService candyService;

    @Autowired
    private CandyUserService candyUserService;

    @Autowired
    private TokenInfoService tokenInfoService;

    @Autowired
    private CandyAboutService candyAboutService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private UserGeneralizeService userGeneralizeService;


    /**
     * 公告信息
     *
     * @return
     */
    @RequestMapping(value = "/about", method = RequestMethod.GET)
    public Object about(HttpServletRequest request, HttpServletResponse response) {
        List<CandyAboutEntity> aboutEntityList = candyAboutService.queryCandyAboutList();

        return ResponseBuilder.custom().success("success", 0).data(aboutEntityList).build();
    }

    /**
     * 获取各种的List
     *
     * @return
     */
    @RequestMapping(value = "/tokenInfo", method = RequestMethod.GET)
    public Object tokenInfo(HttpServletRequest request, HttpServletResponse response) {

        String registerMail = request.getParameter("registerMail");

        HashMap<String,Object> map = new HashMap<>();
        map.put("mail",registerMail);

//        CandyUserEntity user = candyUserService.queryCandyUser(map);

        List<TokenInfoEntity> tokenEntityList = tokenInfoService.queryCandyTokenList();

        HashMap<String,Object> returnMap = new HashMap<>();
        returnMap.put("list",tokenEntityList);

        //所有用户的币数量总和
        returnMap.put("userCandyCount",userGeneralizeService.getUserCandyCount());
//        returnMap.put("user",user);

        return ResponseBuilder.custom().success("success", 0).data(returnMap).build();
    }

    /**
     * 发送邮箱，进行注册
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/registerCandy", method = RequestMethod.POST)
    public Object registerCandy(HttpServletRequest request, HttpServletResponse response) {
        String returnMessage = null;
        String invitecode = request.getParameter("code");

        Map<String, String> objMap = new HashMap<>();
        try {

            //6位生成随机数
            String randomNumbers = RandomUtil.randomNumbers(6);
            //目前为只发邮箱即可登录 后面需要账号密码
            String registerMail = request.getParameter("registerMail");
            //判断中英 三元表达式
            String language = "";
            if (StrUtil.isEmpty(language)) {
                language = "cn";
            }
            //邮箱返回信息
            String sendInfo = "";

            //放入redis 缓存。。设置验证码有效期
            String existRedis = stringRedisTemplate.opsForValue().get(registerMail);//根据key获取缓存中的val
            //缓存没有 。放入缓存,分钟有效
            if (StrUtil.isEmpty(existRedis)) {
                //向redis里存入数据和设置缓存时间
                stringRedisTemplate.opsForValue().set(registerMail, randomNumbers, 120, TimeUnit.SECONDS);
            } else {

                returnMessage = "false";
                objMap.put("result", returnMessage);
                return ResponseBuilder.custom().success("success", 0).data(objMap).build();
            }
            //发送验证码内容 判断中文、英文
            if (language.equals("en")) {
                sendInfo = (String) stringRedisTemplate.opsForHash().get(BIGKEY, "candyEnHead") + "&"
                        + (String) stringRedisTemplate.opsForHash().get(BIGKEY, "candyEn");
            } else {
                sendInfo = (String) stringRedisTemplate.opsForHash().get(BIGKEY, "candyCnHead") + "&"
                        + (String) stringRedisTemplate.opsForHash().get(BIGKEY, "candyCn");
            }

            if (StrUtil.isEmpty(existRedis)) {
                if (StrUtil.isNotEmpty(registerMail)) {

//                    暂时注释。。节约发邮件
                MailAccount account = new MailAccount();
                account.setHost(this.host); //smtp 服务器地址
                account.setPort(Integer.parseInt(this.port));	//端口
                account.setFrom(this.from); // 发信人
                account.setUser(this.user); //账号
                account.setPass(this.passwd); //密码

                String content = sendInfo.split("&")[0] + randomNumbers + sendInfo.split("&")[1];
                //发送邮件
                MailUtil.send(account, registerMail, sendInfo.split("&")[0], content, true);

                    objMap.put("result", "true");

                    //登录操作
                    HashMap<String, Object> paramMap = new HashMap<>();
                    //rsa 解密
                    paramMap.put("mail", registerMail);

                    //判断用户是否存在，没有进行注册保存信息
                    CandyUserEntity candyUserEntity = candyUserService.queryCandyUser(paramMap);

                    if (candyUserEntity == null) {
                        CandyUserEntity saveUser = new CandyUserEntity();
                        if (!StrUtil.isEmpty(invitecode)) {

                            //通过邀请码查询邀请者
                            HashMap<String, Object> map = new HashMap<>();
                            map.put("invitecode", invitecode);
                            CandyUserEntity intiUser = candyUserService.queryCandyUser(map);
                            saveUser.setPromoterId(intiUser.getId().intValue());
                        }

                        saveUser.setMail(registerMail);
                        saveUser.setStatus(1);

                        //生成邀请码
                        String randomString = RandomUtil.randomString(12);
                        //为了邀请码保证唯一性。 虽然重复几率很小，但是还是先查一次缓存一次缓存
                        String codeRedis = (String) stringRedisTemplate.opsForHash().get(MAILMARK, randomString);
                        //如果有，重新生成一次
                        if (!StrUtil.isEmpty(codeRedis)) {
                            randomString = RandomUtil.randomString(12);
                        }
                        saveUser.setInvitecode(randomString);
                        saveUser.setCandycount(100);
                        candyUserService.saveCandyUserId(saveUser);

                        //获取注册者的ID，然后于邀请者进行绑定
                        Long inviteId = saveUser.getId();
                        //返币。邀请者返回第一层。。。表candybonus 没层返币的数量
                        userGeneralizeService.calcBonus(inviteId);

                    }

                } else {
                    returnMessage = "异常情况，请检查邮箱是否正常";
                }

            }

            return ResponseBuilder.custom().success("success", 0).data(objMap).build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseBuilder.custom().success("erro", 0).data(objMap).build();
        }

    }


    /**
     * 判断验证码是否有效
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/judgeCode", method = RequestMethod.GET)
    public Object judgeCode(HttpServletRequest request, HttpServletResponse response) {
        String returnMessage = "";
        String authCode = request.getParameter("authCode");
        String registerMail = request.getParameter("registerMail");
        String existRedis = stringRedisTemplate.opsForValue().get(registerMail);//判断验证码是否有效

        Map<String, String> objMap = new HashMap<>();

        if (!existRedis.equals(authCode)) {
            returnMessage = "false";
        } else {
            returnMessage = "true";
        }
        objMap.put("result", returnMessage);
        return ResponseBuilder.custom().success("success", 0).data(objMap).build();

    }

    /**
     * 注册或者登录操作
     *
     * @param request
     * @param response
     * @return
     * @comment 注册和登录都需要传入registerMail candyPasswd  登录需要regisOrlogin = 0
     */
    @RequestMapping(value = "/loginCandy", method = RequestMethod.GET)
    public Object loginCandy(HttpServletRequest request, HttpServletResponse response) {

        Map<String, String> resultMap = new HashMap<>();
        //账号、密码
//        String candyUser = "2";// request.getParameter("candyUser");
        String candyPasswd = request.getParameter("candyPasswd");
        String registerMail = request.getParameter("registerMail");


        String flag = "false";
        //生成邀请码
        String inviteCode = RandomUtil.randomString(12);
        //为了邀请码保证唯一性。 虽然重复几率很小，但是还是先查一次缓存一次缓存
        String codeRedis = (String) stringRedisTemplate.opsForHash().get(MAILMARK, inviteCode);
        //如果有，重新生成一次
        if (!StrUtil.isEmpty(codeRedis)) {
            inviteCode = RandomUtil.randomString(12);
        }

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("mail", registerMail);
        //判断用户是否存在，没有进行注册保存信息
        CandyUserEntity candyUserEntity = candyUserService.queryCandyUser(paramMap);
        if (candyUserEntity == null) {

            //注册操作
            //rsa 加密
            String pwd = candyPasswd;
            flag = "true";
            //当注册的时候已经添加了用户，但是没有密码，这里只需要更新密码即可
            CandyUserEntity cu = new CandyUserEntity();
            cu.setPasswd(pwd);
            cu.setMail(registerMail);
            cu.setInvitecode(inviteCode);
            cu.setCandycount(100);
            cu.setStatus(1);

            candyUserService.save(cu);
        } else {
            if (StrUtil.isEmpty(candyUserEntity.getPasswd())) {
                candyUserEntity.setPasswd(candyPasswd);
                candyUserService.update(candyUserEntity);
                flag = "true";
                resultMap.put("invitecode", candyUserEntity.getInvitecode());
            }

            if (!candyUserEntity.getPasswd().equals(candyPasswd)) {
                flag = "false";
                resultMap.put("message", "密码不正确!");
            } else {
                //正常登陆
                flag = "true";
            }
        }
        resultMap.put("result", flag);
        resultMap.put("registerMail", registerMail);
        return ResponseBuilder.custom().success("success", 0).data(resultMap).build();
    }

    /**
     * 获取用户推荐后。。6层关系的用户统计
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/statisticsUserCount", method = RequestMethod.GET)
    public Object statisticsUserCount(HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, Object> paramMap = new HashMap<>();
        String registerMail = request.getParameter("registerMail");
        paramMap.put("mail", registerMail);

        //判断用户是否存在，没有进行注册保存信息
        CandyUserEntity candyUserEntity = candyUserService.queryCandyUser(paramMap);


        Map<String, String> objMap = new HashMap<>();

        PrometorUserStatistics prometorUserStatistics = userGeneralizeService.getSubUserStatistics(candyUserEntity.getId());
        objMap.put("lv1", prometorUserStatistics.getLv1().toString());
        objMap.put("lv2", prometorUserStatistics.getLv2().toString());
        objMap.put("lv3", prometorUserStatistics.getLv3().toString());
        objMap.put("lv4", prometorUserStatistics.getLv4().toString());
        objMap.put("lv5", prometorUserStatistics.getLv5().toString());
        objMap.put("lv6", prometorUserStatistics.getLv6().toString());






        objMap.put("mycandycount", candyUserEntity.getCandycount().toString());
        objMap.put("myinvitecode", candyUserEntity.getInvitecode().toString());
        objMap.put("registerMail", candyUserEntity.getMail());

        return ResponseBuilder.custom().success("success", 0).data(objMap).build();

    }

}
